package com.ydkj.a37e_mall.Classes.Acitivity.BaseActivity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.google.gson.Gson;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.pingplusplus.android.Pingpp;
import com.ydkj.a37e_mall.Classes.Applicatiom.MyApplication;
import com.ydkj.a37e_mall.Classes.Model.Request.OrderPayReq;
import com.ydkj.a37e_mall.R;
import com.ydkj.a37e_mall.Resource.Utils.Async_http_post;
import com.ydkj.a37e_mall.Resource.Utils.CommonUtil;
import com.ydkj.a37e_mall.Resource.Utils.Const;
import com.ydkj.a37e_mall.Resource.Utils.SharedPreferencesUtil;
import com.ydkj.a37e_mall.Resource.View.CustomProgressDialog;
import com.ydkj.a37e_mall.Resource.View.OnPasswordInputFinish;
import com.ydkj.a37e_mall.Resource.View.PasswordView;
import com.ydkj.a37e_mall.Resource.View.StatusBarUtil;

import org.json.JSONObject;

import java.io.IOException;
import java.text.DecimalFormat;

import cz.msebera.android.httpclient.Header;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by hong on 2016/4/1.
 * <p>
 * 支付方式
 */
public class PayMoney extends Activity implements View.OnClickListener {

    private Activity mActivity;
    private ImageView img_back;
    private TextView tv_pay_price;
    private LinearLayout lly_pay_weixin, lly_pay_zhifubao, lly_pay_tb, lly_pay_yinlian, lly_pay_balance;
    private String order_id;
    private SharedPreferencesUtil sharedPreferencesUtil;
    private MyApplication myApplication;
    private String all_price;
    private String paytype;
    public static final int PLUGIN_VALID = 0;
    public static final int PLUGIN_NOT_INSTALLED = -1;
    public static final int PLUGIN_NEED_UPGRADE = 2;

    DecimalFormat df = new DecimalFormat("###.00");

    static Activity paymoney;
    String order_sn;

    //回调地址
    public String redirect_url;

    private static final int SDK_PAY_FLAG = 1;

    private static final int SDK_CHECK_FLAG = 2;

    // IWXAPI 是第三方app和微信通信的openapi接口

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.select_pay_tpye);
        mActivity = this;
        paymoney = this;
        init();

//        initWindow();//沉浸式状态栏
    }

    private void initWindow() {
        StatusBarUtil.setColor(mActivity, getResources().getColor(R.color.e50011), 0);
    }

    private void init() {
        sharedPreferencesUtil = SharedPreferencesUtil.getInstance(mActivity);
        myApplication = MyApplication.getInstance();

        tv_pay_price = (TextView) mActivity.findViewById(R.id.tv_pay_price);

        if (this.getIntent().getExtras() != null) {

            order_id = getIntent().getExtras().getString("order_id");
            all_price = getIntent().getExtras().getString("order_price");
            tv_pay_price.setText(all_price);
            order_sn = getIntent().getExtras().getString("order_sn");

            Log.e("ssss1", "order_id==" + order_id);
            Log.e("ssss1", "order_price==" + all_price);
            Log.e("ssss1", "order_sn==" + order_sn);
        }
        img_back = (ImageView) mActivity.findViewById(R.id.img_back);
        lly_pay_weixin = (LinearLayout) mActivity.findViewById(R.id.lly_pay_weixin);
        lly_pay_zhifubao = (LinearLayout) mActivity.findViewById(R.id.lly_pay_zhifubao);
        lly_pay_tb = (LinearLayout) mActivity.findViewById(R.id.lly_pay_tb);
        lly_pay_yinlian = (LinearLayout) mActivity.findViewById(R.id.lly_pay_yinlian);
        lly_pay_balance = (LinearLayout) mActivity.findViewById(R.id.lly_pay_balance);
        img_back.setOnClickListener(this);
        lly_pay_weixin.setOnClickListener(this);
        lly_pay_zhifubao.setOnClickListener(this);
        lly_pay_tb.setOnClickListener(this);
        lly_pay_yinlian.setOnClickListener(this);
        lly_pay_balance.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.img_back:
                finish();
                break;
            case R.id.lly_pay_weixin:
                GetOrderPay(1, 1, "");

//                Pingpp.createPayment(mActivity, "123", "qwalletXXXXXXX");
                break;
            case R.id.lly_pay_zhifubao:
                GetOrderPay(2, 2, "");
//
//                Pingpp.createPayment(mActivity, "456", "qwalletXXXXXXX");

                break;
            case R.id.lly_pay_tb:
                paytype = "通宝支付";
                PopEnterPassword popEnterPassword = new PopEnterPassword(this);

                // 显示窗口
                popEnterPassword.showAtLocation(this.findViewById(R.id.layoutContent),
                        Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0); // 设置layout在PopupWindow中显示的位置
                break;

            case R.id.lly_pay_yinlian:
//                Pingpp.createPayment(mActivity, "789", "qwalletXXXXXXX");
                break;

            case R.id.lly_pay_balance:
                paytype = "余额支付";
                PopEnterPassword popEnterPassword1 = new PopEnterPassword(this);

                // 显示窗口
                popEnterPassword1.showAtLocation(this.findViewById(R.id.layoutContent),
                        Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0); // 设置layout在PopupWindow中显示的位置
                break;
        }
    }

//    private class PayTypeAdapter extends BaseAdapter {
//        private List<GetPayTypeResp.ResultEntity.DataEntity> payTypeList;
//
//        private PayTypeAdapter(List<GetPayTypeResp.ResultEntity.DataEntity> info) {
//            if (info == null) {
//                info = new ArrayList<GetPayTypeResp.ResultEntity.DataEntity>();
//            }
//            payTypeList = info;
//        }
//
//        @Override
//        public int getCount() {
//            return payTypeList.size() - 1;
//        }
//
//        @Override
//        public GetPayTypeResp.ResultEntity.DataEntity getItem(int position) {
//            return payTypeList.get(position);
//        }
//
//        @Override
//        public long getItemId(int position) {
//            return position;
//        }
//
//        @Override
//        public View getView(final int position, View convertView, ViewGroup parent) {
//            ViewHolder vh = null;
//            if (convertView == null) {
//                convertView = LayoutInflater.from(mActivity).inflate(R.layout.select_pay_type_listitem, null);
//                vh = new ViewHolder();
//                vh.img_pay_type = (ImageView) convertView.findViewById(R.id.img_pay_type);
//                vh.tv_pay_type = (TextView) convertView.findViewById(R.id.tv_pay_type);
//
//            } else {
//                vh = (ViewHolder) convertView.getTag();
//            }
//            convertView.setTag(vh);
//            convertView.setClickable(true);
//
//            final ViewHolder finalVh = vh;
//            convertView.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    //支付宝
//                    if (position == 0) {
//
//                        pay_type = 1;
//                        GetOrderPay(1);
//                    }
//
////                    //银联
////                    if (position == 1) {
////                        pay_type = 2;
////                        GetOrderPay(2);
////                    }
//
//                    //微信支付
//                    if (position == 2) {
//                        pay_type = 3;
////                        GetOrderPay(3);
//                    }
//                }
//            });
//            vh.tv_pay_type.setText(getItem(position).getName());
//
//            if (position == 0) {//支付宝
//                finalVh.img_pay_type.setImageDrawable(getResources().getDrawable(R.mipmap.alipay));
//            } else if (position == 1) {//银联
//                finalVh.img_pay_type.setImageDrawable(getResources().getDrawable(R.mipmap.unionpay));
//            } else if (position == 2) {//微信支付
//                finalVh.img_pay_type.setImageDrawable(getResources().getDrawable(R.mipmap.wxpay));
//            }
//            return convertView;
//        }
//
//        private class ViewHolder {
//            private ImageView img_pay_type;
//            public TextView tv_pay_type;
//        }
//    }
//
//    //获取支付方式列表
//    private void GetPayType() {
//        CustomProgressDialog.createDialog(mActivity).Show();
//        GetPayTypeReq req = new GetPayTypeReq();
//        RequestParams params = new RequestParams();
//        params.put("secret", req.getString());
//        String url = Const.COMMON_ADDRESS + req.urlString();
//        Async_http_get.get(url, params, new JsonHttpResponseHandler() {
//            @Override
//            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
//                super.onSuccess(statusCode, headers, response);
//                CustomProgressDialog.Dismiss();
//                Log.e("url", "pay_type_json==" + response);
//                String errno = response.optString("errno");
//                String errmsg = response.optString("errmsg");
//                if (errno.equals("000")) {
//                    GetPayTypeResp resp = GsonImpl.get().toObject(response.toString(), GetPayTypeResp.class);
//                    payTypeAdapter = new PayTypeAdapter(payTypeList);
//                    lv_select_pay_type.setAdapter(payTypeAdapter);
//                    payTypeList.addAll(resp.getResult().getData());
//                    payTypeAdapter.notifyDataSetChanged();
//                    Log.e("url", "payTypeList==" + payTypeList.get(0).getName());
//                } else {
//                    CommonUtil.showToast(mActivity, errmsg);
//                }
//            }
//
//            @Override
//            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
//                super.onFailure(statusCode, headers, responseString, throwable);
//                CustomProgressDialog.Dismiss();
//                CommonUtil.showToast(mActivity, "网络连接失败2222");
//            }
//        });
//    }


    class PaymentTask extends AsyncTask<PaymentRequest, Void, String> {

        @Override
        protected void onPreExecute() {
            //按键点击之后的禁用，防止重复点击
//            wechatButton.setOnClickListener(null);
//            alipayButton.setOnClickListener(null);
//            upmpButton.setOnClickListener(null);
//            bfbButton.setOnClickListener(null);
//            qpayButton.setOnClickListener(null);
        }

        @Override
        protected String doInBackground(PaymentRequest... pr) {

            PaymentRequest paymentRequest = pr[0];
            String data = null;
            String json = new Gson().toJson(paymentRequest);
            try {
                //向Your Ping++ Server SDK请求数据
                data = postJson("http://218.244.151.190/demo/charge", json);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return data;
        }

        /**
         * 获得服务端的charge，调用ping++ sdk。
         */
        @Override
        protected void onPostExecute(String data) {
            if (null == data) {
                showMsg("请求出错", "请检查URL", "URL无法获取charge");
                return;
            }
            Log.d("charge", data);
//            Pingpp.createPayment(ClientSDKActivity.this, data);
            //QQ钱包调起支付方式  “qwalletXXXXXXX”需与AndroidManifest.xml中的data值一致
            //建议填写规则:qwallet + APP_ID
            Log.e("ssss", "wewewe==>" + data);
//            Pingpp.createPayment(mActivity, data, "qwalletXXXXXXX");
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        //支付页面返回处理
        if (requestCode == Pingpp.REQUEST_CODE_PAYMENT) {
            if (resultCode == Activity.RESULT_OK) {
//                String result = data.getExtras().getString("pay_result");
//                /* 处理返回值
//                 * "success" - payment succeed
//                 * "fail"    - payment failed
//                 * "cancel"  - user canceld
//                 * "invalid" - payment plugin not installed
//                 */
//                String errorMsg = data.getExtras().getString("error_msg"); // 错误信息
//                String extraMsg = data.getExtras().getString("extra_msg"); // 错误信息
//                showMsg(result, errorMsg, extraMsg);


                Intent intent = new Intent(mActivity, MyOrderActivity.class);
                startActivity(intent);


            }
        }
    }

    public void showMsg(String title, String msg1, String msg2) {
        String str = title;
        if (null != msg1 && msg1.length() != 0) {
            str += "\n" + msg1;
        }
        if (null != msg2 && msg2.length() != 0) {
            str += "\n" + msg2;
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);
        builder.setMessage(str);
        builder.setTitle("提示");
        builder.setPositiveButton("OK", null);
        builder.create().show();
    }

    //    //用订单号来确定付款
    private void GetOrderPay(final int code, int pay_type_id, String payout_password) {
        CustomProgressDialog.createDialog(mActivity).Show();
        OrderPayReq req = new OrderPayReq();
        req.setUuid(myApplication.getDataEntity().getUuid());
        req.setId(order_id);
        req.setPay_type_id(pay_type_id + "");
        req.setPayout_password(payout_password);


        RequestParams params = new RequestParams();

        params.put("token", sharedPreferencesUtil.getAccessToken());
        params.put("secret", req.getSecret());

        Log.e("ssss1", "tokem==>" + sharedPreferencesUtil.getAccessToken());

        Async_http_post.post(Const.COMMON_ADDRESS + req.urlString(), params, new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                CustomProgressDialog.Dismiss();
                Log.e("url", "putong_json==" + response);
                String errno = response.optString("errno");
                String errmsg = response.optString("errmsg");
                if (errmsg.equals("订单不存在")) {
                    CommonUtil.showToast(mActivity, errmsg);
                    finish();
                    return;
                }
                if (errno.equals("000")) {
                    if (code == 1 || code == 2) {
                        JSONObject result = response.optJSONObject("result");
                        String data = result.optString("data");
                        Log.e("ssss", "data==" + data);
                        Pingpp.createPayment(mActivity, data, "qwallet11111122223");
                    }

//                    Intent intent = new Intent(mActivity, MyOrderActivity.class);
//                    startActivity(intent);
                } else {

                    CommonUtil.showToast(mActivity, errmsg);
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                super.onFailure(statusCode, headers, responseString, throwable);
                CustomProgressDialog.Dismiss();
                CommonUtil.showToast(mActivity, "网络连接失败1111");
            }
        });
    }


    private static String postJson(String url, String json) throws IOException {
        MediaType type = MediaType.parse("application/json; charset=utf-8");
        RequestBody body = RequestBody.create(type, json);
        Request request = new Request.Builder().url(url).post(body).build();

        OkHttpClient client = new OkHttpClient();
        Response response = client.newCall(request).execute();

        return response.body().string();
    }


    //仿微信支付
    public class PopEnterPassword extends PopupWindow {

        private PasswordView pwdView;

        private View mMenuView;

        private Activity mContext;

        private TextView price;

        public PopEnterPassword(final Activity context) {

            super(context);

            this.mContext = context;

            LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            mMenuView = inflater.inflate(R.layout.pop_enter_password, null);

            pwdView = (PasswordView) mMenuView.findViewById(R.id.pwd_view);


            //添加密码输入完成的响应
            pwdView.setOnFinishInput(new OnPasswordInputFinish() {
                @Override
                public void inputFinish(String password) {
                    if (paytype.equals("通宝支付")) {
                        GetOrderPay(3, 3, password);
                    } else {
                        GetOrderPay(3, 5, password);
                    }


                    dismiss();

//                    Toast.makeText(mContext, "支付成功，密码为：" + password, Toast.LENGTH_SHORT).show();
                }
            });
            //总价
            pwdView.setPrice().setText(all_price + "");

            //支付的类型
            pwdView.setType().setText(paytype);

            // 监听X关闭按钮
            pwdView.getImgCancel().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dismiss();
                }
            });

            // 监听键盘上方的返回
            pwdView.getVirtualKeyboardView().getLayoutBack().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dismiss();
                }
            });


            // 设置SelectPicPopupWindow的View
            this.setContentView(mMenuView);
            // 设置SelectPicPopupWindow弹出窗体的宽
            this.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
            // 设置SelectPicPopupWindow弹出窗体的高
            this.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
            // 设置SelectPicPopupWindow弹出窗体可点击
            this.setFocusable(true);
            // 设置SelectPicPopupWindow弹出窗体动画效果
            this.setAnimationStyle(R.style.pop_add_ainm);
            // 实例化一个ColorDrawable颜色为半透明
            ColorDrawable dw = new ColorDrawable(0x66000000);
            // 设置SelectPicPopupWindow弹出窗体的背景
            this.setBackgroundDrawable(dw);

        }
    }

    class PaymentRequest {
        String channel;
        int amount;

        public PaymentRequest(String channel, int amount) {
            this.channel = channel;
            this.amount = amount;
        }
    }
}
